package ro.isdc.training.ejb3.systemuser.dao.ejb;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import ro.isdc.training.ejb3.systemuser.dao.SystemUserDAO;
import ro.isdc.training.ejb3.systemuser.domain.SystemUser;
import ro.isdc.training.ejb3.systemuser.domain.SystemUserId;

/**
 * System User Data Access Object Implementation
 * 
 * All method will be REQUIRED using EJB3 Transactions by default.
 * The bean will be accessed locally by default and should be not exposed to the
 * outside world.
 * 
 * @author Andrei Chirila
 */
@Stateless
public class SystemUserDAOBean implements SystemUserDAO {

	@PersistenceContext
	private EntityManager entityManager;
	
	public SystemUser findSystemUserByIdentification(final SystemUserId systemUserId) {
		List<Object> paramValuesList = new ArrayList<Object>();
    List<String> paramNamesList = new ArrayList<String>();
    
    String sql ="select su from SystemUser su";
    if (systemUserId != null) {
    	if (systemUserId.getEntityId() > 0) {
    		sql += " where su.entityId = :entityId";
    		paramNamesList.add("entityId");
    		paramValuesList.add(systemUserId.getEntityId());
    	} else {
    		sql += " where su.username = :username";
    		paramNamesList.add("username");
    		paramValuesList.add(systemUserId.getUsername());
    	}
    }
    
		return 
    	(SystemUser) entityManager.createQuery(sql).setParameter(paramNamesList.get(0), paramValuesList.get(0)).getSingleResult();
	
	}

	@SuppressWarnings("unchecked")
	public List<SystemUser> findSystemUsers() {
		return entityManager.createNativeQuery("select * from System_Users",
				SystemUser.class).getResultList();
	}

	public Serializable save(final SystemUser systemUser) {
		entityManager.persist(systemUser);
		return systemUser.getEntityId();
	}

	public SystemUser update(final SystemUser systemUser) {
		entityManager.merge(systemUser);
		return systemUser;
	}

}
